'use strict';

export default class extends think.Controller {
  // 初始化操作
  async __before() {
    // 进行登陆判断
    const is_login = await this.is_login();
    if (!is_login) {
      return this.fail('请重新登陆！');
    }
    this.shop_userinfo = await this.session('shop_userinfo');
    if (!this.shop_userinfo.headimg) {
      this.shop_userinfo.headimg = this.config('HEAD_IMG');
    }
    // 跨域全局设置
    this.setCors();
  }

  // 判断是否登陆
  async is_login() {
    // 通过token判断是否登录
    let token = this.header('token');
    if (!token) {
      return false;
    } else {
      // 验证token是否有效（解码token）
      token = new Buffer(token, 'base64').toString();
      const S = require('../login/secret.js');
      const secret = new S();
      token = token.split('.');
      let url = this.ctx.request.url;
      const index = url.indexOf('?');
      if (index > -1) {
        url = url.substr(0, index);
      }
      if (token[3] != '/' + url.split('/').slice(3).join('/')) {
        return false;
      }
      if (secret.createHmac(token[0] + '.' + token[1]) == token[2]) {
        const specialSecret = secret.decipherbase64(token[1]);
        const userinfo = await this.model('or_admin').where({id: specialSecret.uid}).find();
        await this.session('shop_userinfo', userinfo);
        return userinfo.id;
      } else {
        return false;
      }
    }
  }

  // 更新用户session
  async update_session() {
    const is_login = await this.is_login();
    if (is_login) {
      const userinfo = await this.model('or_admin').where({id: is_login}).find();
      await this.session('shop_userinfo', userinfo);
      return true;
    } else {
      return false;
    }
  }

  setCors() {
    const method = this.userAgent.toLowerCase();
    if (method === 'options') {
      this.setCorsHeader();
      this.end();
      return;
    }
    this.setCorsHeader();
  }
  setCorsHeader() {
    this.header('Access-Control-Allow-Origin', this.header('origin') || '*');
    this.header('Access-Control-Allow-Headers', 'x-requested-with');
    this.header('Access-Control-Request-Method', 'GET,POST,PUT,DELETE');
    this.header('Access-Control-Allow-Credentials', 'true');
  }

  // 获取订单编号
  async getordersn(headstr, type) {
    // 查询该店有没有该单号的num没有新增，日期不是今天重置日期和num，有的话num+1
    const nowdate = new Date();
    let datemonth = nowdate.getMonth();
    let dateday = nowdate.getDate();
    datemonth += 1;
    datemonth = datemonth < 10 ? '0' + datemonth : datemonth;
    dateday = dateday < 10 ? '0' + dateday : dateday;
    const today = nowdate.getFullYear() + '-' + datemonth + '-' + dateday;
    const isexist = await this.model('or_autonum')
      .where({departmentid: this.shop_userinfo.departmentid, shortorder: headstr})
      .find();
    let dataarr, res;
    if (think.isEmpty(isexist) || isexist.addtime != today) {
      dataarr = {
        'departmentid': this.shop_userinfo.departmentid,
        'adminid': this.shop_userinfo.id,
        'addtime': today,
        'num': 1,
        'type': type,
        'shortorder': headstr,
        'id': isexist.id
      };
      if (isexist.id) {
        res = await this.model('or_autonum').where({id: isexist.id}).update(dataarr);
      } else {
        res = await this.model('or_autonum').add(dataarr);
      }
    } else {
      dataarr = {
        'num': isexist.num + 1
      };
      res = await this.model('or_autonum')
        .where({departmentid: this.shop_userinfo.departmentid, shortorder: headstr})
        .update(dataarr);
    }
    let snnum = '00000' + dataarr.num;
    snnum = headstr + today + '-' + snnum.substring(snnum.length - 5, snnum.length);
    return res ? snnum : this.fail('生成订单号失败！');
  }

  // 查询是否在跨店操作订单，不允许跨店操作订单
  async isCanEditOrder(orderId, ordreType) {
    let orderShopId;
    switch (ordreType) {
      case 'KKD':
      case 'CZD':
      case 'LSD':
      case 1:
      case 2:
      case 3:
        orderShopId = await this.model('or_shop_order').where({id: orderId}).getField('departmentid', true);
    }
    return orderShopId === this.shop_userinfo.departmentid;
  }
}
